package com.kingsoft.miot.bridge.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.kingsoft.miot.bridge.common.CommonResult;
import com.kingsoft.miot.bridge.controller.req.ManagerEditReqBody;
import com.kingsoft.miot.bridge.controller.req.ManagerFormReq;
import com.kingsoft.miot.bridge.pojo.hotel.HotelInfo;
import com.kingsoft.miot.bridge.pojo.manager.GroupInfo;
import com.kingsoft.miot.bridge.pojo.manager.ManagerInfo;
import com.kingsoft.miot.bridge.pojo.pub.AreaInfo;
import com.kingsoft.miot.bridge.service.AreaService;
import com.kingsoft.miot.bridge.service.HotelService;
import com.kingsoft.miot.bridge.service.manager.GroupInfoService;
import com.kingsoft.miot.bridge.service.manager.ManagerService;
import com.kingsoft.miot.bridge.utils.ValidationUtils;

/**
 * 管理员控制器
 * 
 * @author HUJIANQING
 *
 */
@RestController
public class ManagerController extends BaseController {

	private static final Logger LOGGER = LoggerFactory.getLogger(ManagerController.class);

	@Autowired
	private ManagerService managerService;
	@Autowired
	private HotelService hotelService;
	// 角色管理员
	@Autowired
	private GroupInfoService GroupInfoService;
	@Autowired
	private AreaService areaService;

	/**
	 * 创建管理员
	 * 
	 * @param id
	 * @param managerFormReq
	 * @return
	 */
//	@RequiresRoles(value = { "all_manager", "chief_manager", "area_manager", "hotel_manager" }, logical = Logical.OR)
//	@RequiresPermissions(value = { "create.hotel.manager", "create.area.manager",
//			"create.hotel.ordinary.manager" }, logical = Logical.OR)
	@RequestMapping(value = "/data/managers/create_manager", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public String createManager(@RequestBody ManagerFormReq managerFormReq, HttpServletRequest request) {
		try {
			ValidationUtils.validate(managerFormReq);
		} catch (Exception e) {
			return CommonResult.returnJson(false, 400, "新增管理者失败，数据校验未通过。");
		}
		HotelInfo hotelInfo = hotelService.getById(managerFormReq.getHotel_id());
		AreaInfo areaInfo = areaService.getById(managerFormReq.getArea_id());
		if (hotelInfo == null || areaInfo == null) {
			return CommonResult.returnJson(false, 400, "新增管理者失败，数据校验未通过。");
		}
		try {

			HttpSession session = getSession(request);
			String[] juniorArr = null;
			// 1. 判断当前用户的权限列表
			if (session.getAttribute("mng_user_access") == null) {
				return CommonResult.returnJson(false, 400, "请先登录。");
			}

			int permissionCode = managerFormReq.getLevel();
			GroupInfo groupInfo = GroupInfoService.getById(permissionCode);
			if (groupInfo == null) {
				return CommonResult.returnJson(false, 400, "创建管理员失败，权限值违规。");
			}

			// 2.判断能否有足够权限新建用户
			Subject subject = SecurityUtils.getSubject();
			try {
				// 检测是否拥有创建管理员的权限
				subject.checkPermission(groupInfo.getGroup_info_code());
			} catch (Exception e) {
				return CommonResult.returnJson(false, 302, "创建此用户权限不足");
			}
			// 1. 设置基本信息
			ManagerInfo managerInfo = new ManagerInfo();
			/**
			 * 这里的ID实际应为user ID 也就是子用户的ID 需要匹配匹配相同的邮箱账号进行获取
			 *
			 */
			// 随机生成一个
//			managerInfo.setManager_info_id(Integer.valueOf(IDUtil.genIDByCurTime()));

			// 新增管理者

			// 设置相关的信息
			managerInfo.setManager_info_email(managerFormReq.getManager());
			managerInfo.setHotel_info_id(managerFormReq.getHotel_id());
			managerInfo.setArea_info_id(managerFormReq.getArea_id());
			// 设置权限代码
			managerInfo.setGroup_info_id(managerFormReq.getLevel());
			managerService.addManager(managerInfo);
			// 2. 赋予相关角色 需要IAM 这里先做模拟
			return CommonResult.returnJson(true, 200, "新增酒店管理者成功");
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResult.returnJson(false, 500, "新增酒店管理者失败");
		}
	}

	/**
	 * 删除管理者 以及所有权限(超级管理员权限)
	 * 
	 * @param id
	 * @return
	 */
//	@RequiresRoles(value = { "all_manager", "chief_manager", "area_manager", "hotel_manager" }, logical = Logical.OR)
//	@RequiresPermissions(value = { "create.hotel.manager", "create.area.manager",
//			"create.hotel.ordinary.manager" }, logical = Logical.OR)
	@RequestMapping(value = "/data/managers/{manager_id}/delete", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public String deleteManager(@PathVariable String manager_id) {
		if (!NumberUtils.isDigits(manager_id)) {
			LOGGER.error("管理者ID不能为空");
			return CommonResult.returnJson(false, 400, "管理者ID不能为空");
		}
		try {
			int flag = managerService.deleteManagerById(Integer.valueOf(manager_id));
			if (flag != 1) {
				return CommonResult.returnJson(false, 400, "删除管理者失败");
			}
		} catch (Exception e) {
			return CommonResult.returnJson(false, 500, "删除管理者失败");
		}
		return CommonResult.returnJson(true, 200, "删除管理者成功");
	}

	/**
	 * 1. 拥有多种权限控制 2.删除酒店的某个管理员
	 * 
	 * @param id          酒店的ID
	 * @param managerList 酒店人员列表
	 * @return
	 */
//	@RequiresRoles(value = { "all_manager", "chief_manager", "area_manager", "hotel_manager" }, logical = Logical.OR)
//	@RequiresPermissions(value = { "create.hotel.manager", "create.area.manager",
//			"create.hotel.ordinary.manager" }, logical = Logical.OR)
	@RequestMapping(value = "/data/hotels/{id}/delete_manager", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public String removeHotelManager(@PathVariable String id, @RequestBody Map<String, Object> managerMap) {
		if (!NumberUtils.isDigits(id)) {
			LOGGER.error("删除酒店管理人员失败，酒店不在在ID为： " + id + "的值。");
			return CommonResult.returnJson(false, 400, "删除酒店管理人员失败，该酒店不存在。");
		}
		if (managerMap.size() == 0) {
			return CommonResult.returnJson(false, 400, "删除酒店管理人员失败，未传递参数。");
		}
//		if (managerList == null || managerList.size() <= 0) {
//			return CommonResult.returnJson(false, 404, "删除酒店人员失败。");
//		}
		// 数据格式转化 应对需求变更
		List<String> managerList = new ArrayList<>();
		String managerEmail = managerMap.get("manager").toString();
		managerList.add(managerEmail);
		try {
			int hoteflag = hotelService.deleteManager(Integer.valueOf(id), managerList);
			if (hoteflag == -1) {
				LOGGER.error("删除酒店管理人员失败，不存在id为:  " + id + "的酒店");
				return CommonResult.returnJson(false, 400, "删除酒店管理人员失败。");
			}
			// 设置管理人员酒店id为0
			ManagerInfo managerInfo = managerService.getByEmail(managerEmail);
			managerInfo.setHotel_info_id(0);
			managerService.updateManager(managerInfo);
			return CommonResult.returnJson(true, 200, "删除酒店管理人员成功。");
		} catch (Exception e) {
			LOGGER.error("删除酒店管理人员失败" + e.toString());
			return CommonResult.returnJson(false, 500, "删除酒店管理人员失败。");
		}
	}

	/**
	 * 获取所有的管理员
	 * 
	 * @return
	 */
	@RequestMapping("/data/managers")
	public String getAllManager() {
		try {
			return CommonResult.jsonString(managerService.findAll());
		} catch (Exception e) {
			return CommonResult.returnJson(false, 500, "获取管理者数据失败。");
		}
	}

	/**
	 * 编辑、修改管理员
	 * 
	 * @param manager_id
	 * @return
	 */

	@RequestMapping(value = "/data/managers/{manager_id}/edit_manager", produces = "application/json;charset=UTF-8")
	public String editManager(@PathVariable String manager_id, @RequestBody ManagerEditReqBody req) {
		if (!NumberUtils.isDigits(manager_id)) {
			return CommonResult.returnJson(false, 400, "请求参数为空。");
		}
		// 0. 校验当前操作的权限是否拥有修改管理员权限

		// 1. 检验管理员合法性
		ManagerInfo managerInfo = null;
		try {
			ValidationUtils.validate(req);
			managerInfo = managerService.getManagerInfoById(Integer.valueOf(manager_id));
			if (managerInfo == null) {
				return CommonResult.returnJson(false, 400, "未存在改管理员");
			}
			managerInfo.setArea_info_id(req.getArea_list());
			managerInfo.setHotel_info_id(req.getHotel_id());
			// 2. 更新管理员信息 修改IAM
			managerService.updateManager(managerInfo);
			// 3. 更新权限

		} catch (Exception e) {
			LOGGER.error("修改管理员失败！");
			return CommonResult.returnJson(false, 500, "系统内部错误");
		}
		return CommonResult.returnJson(true, 200, "更新管理者成功。");

	}

}
